package com.hjj.homieMatching.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 添加映射路径
        registry.addMapping("/**")
                // 允许的域名
                .allowedOriginPatterns("*")
                // 允许的请求方式
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                // 允许的头信息
                .allowedHeaders("*")
                // 是否允许发送Cookie
                .allowCredentials(true)
                // 跨域允许时间
                .maxAge(3600);
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        // 允许的域名
        config.addAllowedOriginPattern("*");
        // 是否允许发送Cookie
        config.setAllowCredentials(true);
        // 允许的请求方式
        config.addAllowedMethod("*");
        // 允许的头信息
        config.addAllowedHeader("*");
        // 允许暴露的头信息
        config.addExposedHeader("*");
        // 跨域允许时间
        config.setMaxAge(3600L);
        // 添加映射路径
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}